package com.smartinput.sse.controller

import com.smartinput.sse.application.dto.*
import com.smartinput.device.application.service.DeviceService
import com.smartinput.sse.application.service.SSEService
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter
import jakarta.servlet.http.HttpServletResponse
import jakarta.validation.Valid
import org.springframework.security.access.AccessDeniedException

@RestController
@RequestMapping("/api/sse")
class SSEController(
    private val sseService: SSEService,
    private val deviceService: DeviceService
) {
    
    @GetMapping("/events/{userId}")
    fun subscribeToEvents(
        @PathVariable userId: String,
        @RequestParam deviceId: String,
        response: HttpServletResponse
    ): SseEmitter {
        // 验证设备权限
        if (!deviceService.validateDeviceOwnership(deviceId, userId)) {
            throw AccessDeniedException("权限不足")
        }
        
        val emitter = SseEmitter(Long.MAX_VALUE)
        
        // 设置SSE响应头
        response.setHeader("Content-Type", "text/event-stream")
        response.setHeader("Cache-Control", "no-cache")
        response.setHeader("Connection", "keep-alive")
        
        // 注册SSE连接
        sseService.registerConnection(userId, deviceId, emitter)
        
        // 发送连接确认
        sseService.sendEvent(userId, SSEMessage(
            type = "connection_established",
            data = mapOf("deviceId" to deviceId, "timestamp" to System.currentTimeMillis())
        ))
        
        return emitter
    }
    
    @PostMapping("/connect")
    fun connect(
        @RequestParam userId: String,
        @RequestParam deviceId: String
    ): SseEmitter {
        val emitter = SseEmitter(0) // 无超时
        sseService.registerConnection(userId, deviceId, emitter)
        return emitter
    }
    
    @PostMapping("/notification")
    fun sendNotification(@Valid @RequestBody request: NotificationRequest): ResponseEntity<String> {
        // 这里需要从 JWT token 中获取 userId，暂时使用固定值
        val userId = "" // TODO: 从认证上下文获取
        sseService.sendNotification(userId, request)
        return ResponseEntity.ok("通知发送成功")
    }
    
    @GetMapping("/devices/connected")
    fun getConnectedDevices(@RequestParam userId: String): ResponseEntity<List<String>> {
        val devices = sseService.getConnectedDevices(userId)
        return ResponseEntity.ok(devices)
    }
    
    @GetMapping("/devices/{deviceId}/connected")
    fun isDeviceConnected(@PathVariable deviceId: String): ResponseEntity<Map<String, Boolean>> {
        val connected = sseService.isDeviceConnected(deviceId)
        return ResponseEntity.ok(mapOf("connected" to connected))
    }
    
    @DeleteMapping("/disconnect")
    fun disconnect(
        @RequestParam userId: String,
        @RequestParam deviceId: String
    ): ResponseEntity<String> {
        sseService.removeConnection(userId, deviceId)
        return ResponseEntity.ok("连接已断开")
    }
} 